package com.dormitory.service.impl;

import com.dormitory.dao.CheckInDao;
import com.dormitory.dao.RoomDao;
import com.dormitory.dao.impl.CheckInDaoImpl;
import com.dormitory.dao.impl.RoomDaoImpl;
import com.dormitory.model.CheckIn;
import com.dormitory.model.Room;
import com.dormitory.service.CheckInService;

import java.util.List;

public class CheckInServiceImpl implements CheckInService {
    private CheckInDao checkInDao;
    private RoomDao roomDao;

    public CheckInServiceImpl() {
        this.checkInDao = new CheckInDaoImpl();
        this.roomDao = new RoomDaoImpl();
    }

    @Override
    public boolean addCheckIn(CheckIn checkIn) {
        // 1. 查找房间
        Room room = roomDao.findById(checkIn.getRoomId());
        if (room == null) return false;
        // 2. 判断房间状态
        if ("已满".equals(room.getRoomStatus())) {
            // 房间已满，入住失败
            return false;
        }
        // 3. 插入入住信息
        boolean success = checkInDao.save(checkIn);
        if (success) {
            // 4. 更新房间当前人数
            int newOccupancy = room.getCurrentOccupancy() + 1;
            room.setCurrentOccupancy(newOccupancy);
            // 5. 判断是否已满
            if (newOccupancy >= room.getCapacity()) {
                room.setRoomStatus("已满");
            } else {
                room.setRoomStatus("空闲");
            }
            roomDao.update(room);
        }
        return success;
    }

    @Override
    public boolean updateCheckIn(CheckIn checkIn) {
        return checkInDao.update(checkIn);
    }

    @Override
    public boolean deleteCheckIn(Integer checkInId) {
        return checkInDao.delete(checkInId);
    }

    @Override
    public CheckIn getCheckInById(Integer checkInId) {
        return checkInDao.findById(checkInId);
    }

    @Override
    public List<CheckIn> getAllCheckIns() {
        return checkInDao.findAll();
    }

    @Override
    public List<CheckIn> getCheckInsByStudentId(Integer studentId) {
        return checkInDao.findByStudentId(studentId);
    }

    @Override
    public List<CheckIn> getCheckInsByRoomId(Integer roomId) {
        return checkInDao.findByRoomId(roomId);
    }

    @Override
    public List<CheckIn> searchCheckIns(String condition) {
        return checkInDao.findByCondition(condition);
    }
} 